#!/usr/bin/env python3
"""
批量修复数据库中的图片URL
将 http://8.152.193.196:9000 替换为 https://minio.aqilmini.com
"""
from app.core.database import SessionLocal
from app.models.user import User
from app.models.team import Team, TeamMember

def fix_image_urls():
    """修复所有图片URL"""
    db = SessionLocal()
    
    try:
        print("🔧 开始修复图片URL...\n")
        
        old_url = "http://8.152.193.196:9000"
        new_url = "https://minio.aqilmini.com"
        
        fixed_count = 0
        
        # 1. 修复用户头像
        print("👤 修复用户头像...")
        users = db.query(User).all()
        for user in users:
            if user.avatar and old_url in user.avatar:
                old_avatar = user.avatar
                user.avatar = user.avatar.replace(old_url, new_url)
                print(f"  ✅ 用户 {user.nick_name}: {old_avatar} -> {user.avatar}")
                fixed_count += 1
        
        # 2. 修复球队Logo
        print("\n🏃 修复球队Logo...")
        teams = db.query(Team).all()
        for team in teams:
            if team.logo and old_url in team.logo:
                old_logo = team.logo
                team.logo = team.logo.replace(old_url, new_url)
                print(f"  ✅ 球队 {team.name}: {old_logo} -> {team.logo}")
                fixed_count += 1
        
        # 3. 修复球队成员头像
        print("\n👥 修复球队成员头像...")
        members = db.query(TeamMember).all()
        for member in members:
            if member.avatar and old_url in member.avatar:
                old_avatar = member.avatar
                member.avatar = member.avatar.replace(old_url, new_url)
                print(f"  ✅ 成员 {member.user_name}: {old_avatar} -> {member.avatar}")
                fixed_count += 1
        
        # 提交更改
        db.commit()
        
        print(f"\n🎉 修复完成！")
        print(f"📈 总共修复了 {fixed_count} 个URL")
        
    except Exception as e:
        print(f"\n❌ 修复失败: {e}")
        db.rollback()
        raise
    finally:
        db.close()

if __name__ == "__main__":
    fix_image_urls()

